#include <stdio.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <limits.h>

uint8_t buffer[1024];

static void display_inotify_event(struct inotify_event *event)
{
	printf("wd =%2d; ", event->wd);
	printf("\n");
	
	printf("event: ");
	if(event->mask & IN_ACCESS)		
		printf("IN_ACCESS ");
	if(event->mask & IN_ATTRIB)		
		printf("IN_ATTRIB ");
	if(event->mask & IN_CLOSE_NOWRITE)
		printf("IN_CLOSE_NOWRITE ");
	if(event->mask & IN_CLOSE_WRITE)   
		printf("IN_CLOSE_WRITE ");
	if(event->mask & IN_CREATE)		
		printf("IN_CREATE ");
	if(event->mask & IN_DELETE)		
		printf("IN_DELETE ");
	if(event->mask & IN_DELETE_SELF)   
		printf("IN_DELETE_SELF ");
	if(event->mask & IN_IGNORED)	   
		printf("IN_IGNORED ");
	if(event->mask & IN_ISDIR)		 
		printf("IN_ISDIR ");
	if(event->mask & IN_MODIFY)		
		printf("IN_MODIFY ");
	if(event->mask & IN_MOVE_SELF)	
		printf("IN_MOVE_SELF ");
	if(event->mask & IN_MOVED_FROM)	
		printf("IN_MOVED_FROM ");
	if(event->mask & IN_MOVED_TO)	 
		printf("IN_MOVED_TO ");
	if(event->mask & IN_OPEN)		  
		printf("IN_OPEN ");
	if(event->mask & IN_Q_OVERFLOW)	
		printf("IN_Q_OVERFLOW ");
	if(event->mask & IN_UNMOUNT)	   
		printf("IN_UNMOUNT ");
	printf("\n");

	if(event->len > 0)
		printf("name = %s\n", event->name);//该字段的数据紧跟在inotify_event结构体的后面
}

int main(int argv, char *argc[])
{
	int i;
	int inotify_fd;
	ssize_t lenght;
	uint8_t *p_temp;
	struct inotify_event *event;
	
	if(argv < 2)
	{
		printf("parameter error\r\n");
		return -1;
	}
	
	//初始化inotify
	inotify_fd = inotify_init();
	if(inotify_fd == -1)
	{
		perror("inotify_init");
		return -1;
	}
	
	//添加watch
	for(i=1; i<argv; i++)
	{
		if(inotify_add_watch(inotify_fd, argc[i], IN_ALL_EVENTS) == -1) 
		{
			close(inotify_fd);
			perror("inotify_add_watch");
			return -1;
		}
		printf("add \"%s\" succeed\r\n", argc[i]);
	}
	
	//读取事件
	while(1)
	{
		lenght = read(inotify_fd, buffer, sizeof(buffer));
		for(p_temp=buffer; p_temp<buffer+lenght; )
		{
			event = (struct inotify_event *)p_temp;
			display_inotify_event(event);
			p_temp += sizeof(struct inotify_event) + event->len;
		}
	}
	
	return 0;
}